<?php

class DefaultController extends AController {

    public $layout = '//layouts/admin/login';

    public function accessRules() {
        $parentRules = parent::accessRules();
        $myRule = array('allow',
            'actions' => array('captcha', 'test'),
            'users' => array('*'),
        );
        array_unshift($parentRules, $myRule);

        return $parentRules;
    }

    public function actions() {
        return array(
            'captcha' => array(
                'class'       => 'CCaptchaAction',
                'backColor'   => 0xFFFFFF,
                'transparent' => true,
                'foreColor'   => 0x851A1A
            ),
        );
    }

    public function actionIndex() {
        $this->render('index');
    }

    public function actionLogin() {
        $model = new LoginForm;

        if (! Yii::app()->user->isGuest) { //logined
            $this->redirect(Yii::app()->user->returnUrl);
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            if ($model->validate() && $model->login()) {
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }

        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        if (isset(Yii::app()->user->login_log_id) && !empty(Yii::app()->user->login_log_id)) {
            UserIdentity::updateLoginLog(Yii::app()->user);
        }

        Yii::app()->user->logout(false);
        Yii::app()->session->destroy();

        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }
}